package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.entity.couponGift.CouponGiftItem;
import com.burgeon.backend.SHOP.mappers.AppUserMapper;
import com.burgeon.backend.SHOP.mappers.PlusActiveMapper;
import com.burgeon.backend.SHOP.service.AppTemplateService;
import com.burgeon.backend.SHOP.service.PayWechatService;
import com.burgeon.backend.SHOP.service.PlusActiveService;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.SHOPBACKEND.service.BackendCouponGiftService;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.entity.User;
import com.burgeon.backend.service.CouponService;
import com.burgeon.backend.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.burgeon.backend.SHOP.service.Impl.OrderServiceImpl.getOrderIdByUUId;


@Service
public class PlusActiveServiceImpl implements PlusActiveService {

    @Autowired
    private PlusActiveMapper plusActiveMapper;

    @Autowired
    private PayWechatService payWechatService;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private BackendCouponGiftService backendCouponGiftService;

    @Autowired
    private AppTemplateService appTemplateService;

    //plus会员页面数据展示
    @Override
    public HashMap getData(String token,String uid) {
        HashMap data = new HashMap();

        PlusActiveConfiguration plusActiveConfiguration = plusActiveMapper.findInfo(token);
        data.put("originalPrice",plusActiveConfiguration.getOriginalPrice());
        data.put("savingCost",plusActiveConfiguration.getSavingCost());//预计节省金额
        data.put("snapNum",plusActiveConfiguration.getSnapNum());//预计抢购人数
        data.put("preferentialPrice",plusActiveConfiguration.getPreferentialPrice());//开通费用
        data.put("monthCost",plusActiveConfiguration.getMonthCost());//每月预计省

        PlusApplyRecord plusApplyRecord = plusActiveMapper.findState(token,uid);
        if(plusApplyRecord != null ){
            data.put("state",1);//已开通、续费
        }else {
            data.put("state",0);//立即开通
        }

        //plus无门槛券
        List<CouponGiftItem> listThresholdCoupon = plusActiveMapper.findCouponGift(plusActiveConfiguration.getThresholdCouponGiftId());
        ArrayList<Object> ThresholdCouponGiftList = new ArrayList<>();
        for (CouponGiftItem ThresholdCoupon:listThresholdCoupon) {
            for(int i = 0;i<ThresholdCoupon.getCount();i++){
                CouponType couponType = plusActiveMapper.findCoupType(ThresholdCoupon.getTid());
                ThresholdCouponGiftList.add(couponType);
            }
        }
        data.put("ThresholdCouponGift",ThresholdCouponGiftList);

        //plus每月神券
        List<CouponGiftItem> listMonthCoupon = plusActiveMapper.findCouponGift(plusActiveConfiguration.getMonthCouponGiftId());
        ArrayList<Object> MonthCouponGiftList = new ArrayList<>();
        for (CouponGiftItem MonthCoupon: listMonthCoupon) {

            CouponType couponType = plusActiveMapper.findCoupType(MonthCoupon.getTid());
            couponType.setCount(MonthCoupon.getCount());
            MonthCouponGiftList.add(couponType);

        }
        data.put("MonthCouponGift",MonthCouponGiftList);

        //plus商品
        List<Goods> goodsList =  plusActiveMapper.findGoodInfo(token);
        data.put("goods",goodsList);

        //会员到期日期
        String userIsPlus = plusActiveMapper.findUserIsPlus(token,uid);
        if (userIsPlus.equals("Y")){
            String endDate = plusActiveMapper.findUserPlusEnd(token,uid).substring(0,10);
            data.put("endDate",endDate);
        }

        //获取用户信息：头像，姓名
        User userInfo = appUserMapper.findUserInfo(token,uid);
        data.put("userName",userInfo.getName());
        data.put("userImg",userInfo.getImg());

        return data;
    }

    //开通plus会员
    @Override
    public PayData openPlus(String token, String uid , String openid, String total_fee) throws Exception {

        System.err.println("openid===="+openid);
        System.err.println("total_fee===="+total_fee);

        String out_trade_no = getOrderIdByUUId();

        System.err.println(out_trade_no);

        PayData data = new PayData();

        PlusApplyRecord plusApplyRecord = new PlusApplyRecord();

        plusApplyRecord.setState("0");
        plusApplyRecord.setOperation("未支付");
        plusApplyRecord.setUid(uid);
        plusApplyRecord.setToken(token);
        plusApplyRecord.setAmount(total_fee);
        plusApplyRecord.setType("年费");
        plusApplyRecord.setOutTradeNo(out_trade_no);

        Integer row = plusActiveMapper.insetPlusRecord(plusApplyRecord);
        if(row != null){
            System.err.println("recordId======"+plusApplyRecord.getId());
            data.setOrderId(plusApplyRecord.getId().toString());
        }

        String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/plusResult/"+token;

        try {
             data = payWechatService.createUnified(notify_url, openid, token, out_trade_no, total_fee, "Plus会员");
        }catch (Exception e){
            e.printStackTrace();
            throw new ErrorDataExceptionApp(e.getMessage());
        }

        System.err.println("data==="+data);
        return data;
    }

    @Override
    public void upState(String outTradeNo, String token) {
        plusActiveMapper.upState(outTradeNo,token);
    }

    @Override
    public String findUid(String outTradeNo) {
        String uid = plusActiveMapper.findUid(outTradeNo);
        return uid;
    }

    @Override
    public PlusApplyRecord findState(String uid, String token) {
        PlusApplyRecord plusApplyRecord = plusActiveMapper.findState(token,uid);
        return plusApplyRecord;
    }

    @Override
    public void upEndDate(String outTradeNo, String token,String endDate) {
        plusActiveMapper.upEndDate(outTradeNo,token,endDate);
    }

    @Override
    public void upUserIsPlus(String uid,String token) {
        appUserMapper.upUserIsPlus(uid,token);
    }

    public void findSendRecord(String token) throws ErrorDataException {
        /*System.err.println("token==="+token);*/
        List<User> uids = appUserMapper.findUids(token);//获取用户ID
        PlusActiveConfiguration plusActiveConfiguration = plusActiveMapper.findInfo(token);//获取每月神券、无门槛券ID
        if(uids.size()>0 && plusActiveConfiguration != null){
            for (User uid:uids) {
                PlusSendRecord plusSendRecords = plusActiveMapper.findSendRecord(uid.getId(),token);
                if(plusSendRecords == null){//判断当月是否发送过券
                    try {
                        backendCouponGiftService.createCoupon(plusActiveConfiguration.getMonthCouponGiftId().toString(),uid.getPhone(),token);//发送每月神券
                        backendCouponGiftService.createCoupon(plusActiveConfiguration.getThresholdCouponGiftId().toString(),uid.getPhone(),token);//发送无门槛券

                        PlusSendRecord plusSendRecord = new PlusSendRecord();
                        plusSendRecord.setUid(uid.getId());
                        plusSendRecord.setToken(token);
                        plusActiveMapper.addPlusSendRecord(plusSendRecord);//新增发送记录
                    }catch (Exception e){
                        System.err.println("发送出错啦");
                        throw new ErrorDataException("发送出错");
                    }
                }else {
                    throw new ErrorDataException("已经发送过啦");
                }
            }
        }else {
            throw new ErrorDataException("出现错误");
        }

    }

    @Override
    public void sendDueNotice(String token) throws ParseException {
        List<PlusApplyRecord> openDate = plusActiveMapper.findOpenDate(token);

        String dueRemind = plusActiveMapper.findDueRemind(token);//查看到期提醒时间
        System.err.println("到期提醒====="+dueRemind);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        String todayString = sdf.format(today);

        for (PlusApplyRecord data:openDate) {

            String openId = plusActiveMapper.findOpenId(data.getUid(),token);

            Calendar calendar = Calendar.getInstance();

            calendar.setTime(sdf.parse(data.getEndDate()));
            calendar.set(Calendar.DATE,calendar.get(Calendar.DATE) - Integer.parseInt(dueRemind));
            String endDate = sdf.format(calendar.getTime());

            if (!todayString.equals(endDate)){
                continue;
            }
            appTemplateService.sendDueNotice(token,data.getEndDate().substring(0,10),openId);

        }

    }


    /*@Override
    public PlusApplyRecord findOperation(String uid, String token) {
        PlusApplyRecord plusApplyRecordOperation = plusActiveMapper.findOperation(token,uid);
        return plusApplyRecordOperation;
    }*/
}
